package mc.contents.web.common;

import com.alibaba.fastjson.JSON;
import mc.contents.web.CrawConfig;
import mc.contents.web.request.TaskParams;
import mc.contents.web.request.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
 * Created by Administrator on 14-12-8.
 */
public abstract class AbstractPostSender implements Runnable{
    private static Logger log = LoggerFactory.getLogger( AbstractPostSender.class );
    private CrawConfig crawConfig;
    private Long id;
    private String configName;

    public AbstractPostSender( CrawConfig crawConfig,Long id,String configName ) {
        this.crawConfig = crawConfig;
        this.id = id;
        this.configName = configName;
    }

    @Override
    public void run() {
        try{
            log.info( "task {},id {} begin post craw",configName,id );
            List<Task> tasks = buildTaskList();
            sendCrawRequest( configName,tasks );
        }catch ( Exception e ) {
            log.error( "task {},id {} sendCrawRequest error : {} ",configName,id,e.getMessage() );
        }
    }

    public abstract List<Task> buildTaskList();

    private void sendCrawRequest( String configName,List<Task> taskList ){
        TaskParams taskJson = new TaskParams();
        taskJson.setConf( configName );
        taskJson.setUser( crawConfig.getUser() );
        taskJson.setKey( crawConfig.getKey() );
        taskJson.setTimeout( crawConfig.getCrawClientTimeOut() );
        taskJson.setTasks( taskList );

        String taskStr = JSON.toJSONString( taskJson );
        RestTemplate template = new RestTemplate(  );
        String response = template.postForObject( crawConfig.getApiUrl(), taskStr, String.class );
        log.info( id + " template post return : "+ response );
    }

}
